package com.zg.datapush.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zg.common.core.R;
import com.zg.common.core.dao.datapush.dao.DpPushRecordDao;
import com.zg.common.core.dao.datapush.entity.DpPushRecord;
import com.zg.datapush.vo.DpPushRecordVo;
import com.zg.datapush.req.DpPushRecordPageReq;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.stream.Collectors;

/**
 * 推送记录服务（增强版）
 * @author zg
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DpPushRecordService {

    private final DpPushRecordDao pushRecordDao;
    private final DpPushLogService pushLogService;
    private final PushService pushService;

    /**
     * 分页查询推送记录（增强版查询条件）
     */
    public IPage<DpPushRecordVo> page(Page<DpPushRecord> page, DpPushRecordPageReq query) {
        LambdaQueryWrapper<DpPushRecord> wrapper = new LambdaQueryWrapper<>();

        // 基础查询条件
        if (query.getTaskId() != null) {
            wrapper.eq(DpPushRecord::getTaskId, query.getTaskId());
        }
        if (StrUtil.isNotBlank(query.getStatus())) {
            wrapper.eq(DpPushRecord::getStatus, query.getStatus());
        }

        // 新增查询条件
        if (StrUtil.isNotBlank(query.getDocumentType())) {
            wrapper.eq(DpPushRecord::getDocumentType, query.getDocumentType());
        }
        if (StrUtil.isNotBlank(query.getPushMethod())) {
            wrapper.eq(DpPushRecord::getPushMethod, query.getPushMethod());
        }
        if (StrUtil.isNotBlank(query.getTriggerType())) {
            wrapper.eq(DpPushRecord::getTriggerType, query.getTriggerType());
        }

        // 时间范围查询
        if (query.getStartTimeBegin() != null) {
            wrapper.ge(DpPushRecord::getStartTime, new Timestamp(query.getStartTimeBegin().getTime()));
        }
        if (query.getStartTimeEnd() != null) {
            wrapper.le(DpPushRecord::getStartTime, new Timestamp(query.getStartTimeEnd().getTime()));
        }

        wrapper.orderByDesc(DpPushRecord::getStartTime);

        IPage<DpPushRecord> entityPage = pushRecordDao.page(page, wrapper);

        // 转换为VO
        IPage<DpPushRecordVo> voPage = new Page<>();
        BeanUtil.copyProperties(entityPage, voPage);
        voPage.setRecords(entityPage.getRecords().stream()
            .map(entity -> {
                DpPushRecordVo vo = new DpPushRecordVo();
                BeanUtil.copyProperties(entity, vo);
                return vo;
            }).collect(Collectors.toList()));

        return voPage;
    }

    /**
     * 根据ID查询推送记录详情（包含日志详情）
     */
    public DpPushRecordVo getById(Long id) {
        DpPushRecord entity = pushRecordDao.getById(id);
        if (entity == null) {
            return null;
        }

        DpPushRecordVo vo = new DpPushRecordVo();
        BeanUtil.copyProperties(entity, vo);

        // 查询推送日志详情
        vo.setPushLogs(pushLogService.listByRecordId(id));

        return vo;
    }

    /**
     * 手动重推
     */
    public R<String> rePush(Long recordId) {
        try {
            DpPushRecord originalRecord = pushRecordDao.getById(recordId);
            if (originalRecord == null) {
                return R.error("推送记录不存在");
            }

            // 异步执行重推
            pushService.executePushTaskWithRePush(originalRecord.getTaskId(), recordId);

            return R.success("重推任务已启动");
        } catch (Exception e) {
            log.error("启动重推任务失败", e);
            return R.error("启动重推任务失败: " + e.getMessage());
        }
    }
}
